package com.fast.admin.common.handler;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.ApiResult;
import com.baomidou.mybatisplus.extension.api.IErrorCode;
import com.baomidou.mybatisplus.extension.enums.ApiErrorCode;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.fast.common.util.R;
import com.fast.common.util.emuns.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Title：全局异常处理
 * @author：Administrator
 * @date：2018/7/13 12:02
 * @version：1.0
 **/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * <p>
     * 自定义 REST 业务异常
     * <p>
     *
     * @param e 异常类型
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public R handleBadRequest(Exception e) {
        /*
         * 业务逻辑异常
         */
        if (e instanceof ApiException) {
            IErrorCode errorCode = ((ApiException) e).getErrorCode();
            if (null != errorCode) {
                log.debug("Rest request error, {}", errorCode.toString());
                return R.error(Integer.valueOf(errorCode.getCode()), errorCode.getMsg());
            }
            log.debug("Rest request error, {}", e.getMessage());
            return R.error(e.getMessage());
        }

        /*
         * 参数校验异常
         */
        else if (e instanceof BindException) {
            BindingResult bindingResult = ((BindException) e).getBindingResult();
            if (null != bindingResult && bindingResult.hasErrors()) {
                List<Object> jsonList = new ArrayList<>();
                bindingResult.getFieldErrors().stream().forEach(fieldError -> {
                    Map<String, Object> jsonObject = new HashMap<>(2);
                    jsonObject.put("name", fieldError.getField());
                    jsonObject.put("msg", fieldError.getDefaultMessage());
                    jsonList.add(jsonObject);
                });
                return R.error(400, "参数不合法");
            }
        }
        else if (e instanceof IncorrectCredentialsException){
            return R.error(StatusCode.LOGIN_FAILED.getCode(), StatusCode.LOGIN_FAILED.getMessage());
        }
        /**
         * 系统内部异常，打印异常栈
         */
        log.error("Error: handleBadRequest StackTrace : {}", e);
        return R.error("服务器内部错误");
    }
}
